package com.leizi.igym.controller;

import cn.hutool.core.lang.UUID;
import com.leizi.igym.BaseContext.UserThreadLocal;
import com.leizi.igym.constant.FileConstant;
import com.leizi.igym.dto.UploadFileDTO;
import com.leizi.igym.enums.FileUploadBizEnum;
import com.leizi.igym.enums.ReturnCodeEnum;
import com.leizi.igym.exception.BusinessException;
import com.leizi.igym.manager.CosManager;
import com.leizi.igym.pojo.ContextUser;
import com.leizi.igym.resp.Result;
import com.leizi.igym.utils.ThrowUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Objects;

/**
 * @Author: leizi0110
 * @CreateTime: 2024-04-04  10:42
 * @Description:
 */

@RestController
@Slf4j
@Tag(name = "文件相关接口")
@RequestMapping("/file")
public class FileController {

    @Resource
    private CosManager cosManager;

    @Operation(summary = "管理端：上传各种图片")
    @PostMapping("uploadInAdmin")
    public Result<String> uploadInAdmin(@RequestPart("pic") MultipartFile multipartFile,
                                       UploadFileDTO uploadFileDTO) {
        log.info("管理端正在上传文件，上传类型：{}", uploadFileDTO);
        String biz = uploadFileDTO.getBiz();
        FileUploadBizEnum fileUploadBizEnum = FileUploadBizEnum.getEnumByValue(biz);
        if (fileUploadBizEnum == null) {
            throw new BusinessException(ReturnCodeEnum.PARAMS_ERROR);
        }

        // 获取当前管理员对象
        ContextUser contextUser = UserThreadLocal.get();
        ThrowUtils.throwIf(Objects.isNull(contextUser), ReturnCodeEnum.SYSTEM_ERROR);

        // 构造文件
        String uuid = UUID.randomUUID().toString(true);
        String filename = uuid + "-" + multipartFile.getOriginalFilename();
        String filepath = String.format("/%s/%s/%S", fileUploadBizEnum.getValue(), contextUser.getId(), filename);
        File file = null;
        try {
            // 上传文件
            file = File.createTempFile(filepath, null);
            multipartFile.transferTo(file);
            cosManager.putObject(filepath, file);
            // 返回可访问地址
            return Result.ok(FileConstant.COS_HOST + filepath);
        } catch (Exception e) {
            log.error("file upload error, filepath = " + filepath, e);
            throw new BusinessException(ReturnCodeEnum.SYSTEM_ERROR, "上传失败");
        } finally {
            if (file != null) {
                // 删除临时文件
                boolean delete = file.delete();
                if (!delete) {
                    log.error("file delete error, filepath = {}", filepath);
                }
            }
        }
    }

    @Operation(summary = "用户端：上传各种图片")
    @PostMapping("/user/upload")
    public Result<String> uploadInUser(@RequestPart("pic") MultipartFile multipartFile,
                                       UploadFileDTO uploadFileDTO) {
        log.info("用户端正在上传文件，上传类型：{}", uploadFileDTO);
        String biz = uploadFileDTO.getBiz();
        FileUploadBizEnum fileUploadBizEnum = FileUploadBizEnum.getEnumByValue(biz);
        if (fileUploadBizEnum == null) {
            throw new BusinessException(ReturnCodeEnum.PARAMS_ERROR);
        }

        // 获取当前管理员对象
        ContextUser contextUser = UserThreadLocal.get();
        ThrowUtils.throwIf(Objects.isNull(contextUser), ReturnCodeEnum.SYSTEM_ERROR);

        // 构造文件
        String uuid = UUID.randomUUID().toString(true);
        String filename = uuid + "-" + multipartFile.getOriginalFilename();
        String filepath = String.format("/%s/%s/%S", fileUploadBizEnum.getValue(), contextUser.getId(), filename);
        File file = null;
        try {
            // 上传文件
            file = File.createTempFile(filepath, null);
            multipartFile.transferTo(file);
            cosManager.putObject(filepath, file);
            // 返回可访问地址
            return Result.ok(FileConstant.COS_HOST + filepath);
        } catch (Exception e) {
            log.error("file upload error, filepath = " + filepath, e);
            throw new BusinessException(ReturnCodeEnum.SYSTEM_ERROR, "上传失败");
        } finally {
            if (file != null) {
                // 删除临时文件
                boolean delete = file.delete();
                if (!delete) {
                    log.error("file delete error, filepath = {}", filepath);
                }
            }
        }
    }
}
